package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName GulimallExceptionControllerAdvice
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/6/11
 * @Version 1.0
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")  //扫描该路径下的包，获取其抛出的异常,异常信息以Json格式抛出
public class GulimallExceptionControllerAdvice {
    /**
     * 标注这是一个校验异常处理器
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){  //标明要捕获的异常类型
        log.error("数据校验出现问题{},异常类型：{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> map=new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            String field = item.getField();
            String message = item.getDefaultMessage();
            map.put(field,message);
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 公共异常处理器，处理所有未知异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable){
        log.error("数据校验出现问题{},异常类型：{}",throwable.getMessage(),throwable.getClass());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
